const express = require('express');
const router = express.Router();
const Goods = require('../models/Goods');
const Category = require('../models/Category');

// 获取首页轮播图数据
router.get('/findBanner', async (req, res) => {
  try {
    const banners = await Banner.find({ status: 1 }).sort({ sort: 1 });
    res.json({
      code: 200,
      message: '成功',
      data: banners
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '获取轮播图失败',
      data: null
    });
  }
});

// 获取首页分类数据
router.get('/findCategory1', async (req, res) => {
  try {
    const categories = await Category.find({ level: 1 }).sort({ sort: 1 });
    res.json({
      code: 200,
      message: '成功',
      data: categories
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '获取分类失败',
      data: null
    });
  }
});

// 获取首页广告数据
router.get('/advertisement', async (req, res) => {
  try {
    const ads = await Advertisement.find({ status: 1 }).sort({ sort: 1 });
    res.json({
      code: 200,
      message: '成功',
      data: ads
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '获取广告失败',
      data: null
    });
  }
});

// 获取首页商品列表
router.get('/findListGoods', async (req, res) => {
  try {
    const goods = await Goods.find({ status: 1 })
      .sort({ createdAt: -1 })
      .limit(10);
    res.json({
      code: 200,
      message: '成功',
      data: goods
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '获取商品列表失败',
      data: null
    });
  }
});

// 获取首页推荐商品
router.get('/findRecommendGoods', async (req, res) => {
  try {
    const goods = await Goods.find({ status: 1, isRecommend: true })
      .sort({ sales: -1 })
      .limit(6);
    res.json({
      code: 200,
      message: '成功',
      data: goods
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '获取推荐商品失败',
      data: null
    });
  }
});

module.exports = router; 